package com.jihui.jihuipicturebackend.controller;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jihui.jihuipicturebackend.annotation.CheckAuth;
import com.jihui.jihuipicturebackend.api.ailiyunai.aliyunapi.AliYunAiApi;
import com.jihui.jihuipicturebackend.api.ailiyunai.model.CreateOutPaintingTaskResponse;
import com.jihui.jihuipicturebackend.api.ailiyunai.model.GetOutPaintingTaskResponse;
import com.jihui.jihuipicturebackend.common.BaseResponse;
import com.jihui.jihuipicturebackend.common.ResultUtils;
import com.jihui.jihuipicturebackend.constant.UserConstant;
import com.jihui.jihuipicturebackend.exception.BusinessException;
import com.jihui.jihuipicturebackend.exception.ErrorCode;
import com.jihui.jihuipicturebackend.exception.ThrowUtils;
import com.jihui.jihuipicturebackend.manager.auth.SpaceUserAuthManager;
import com.jihui.jihuipicturebackend.manager.auth.StpKit;
import com.jihui.jihuipicturebackend.manager.auth.annotation.SaSpaceCheckPermission;
import com.jihui.jihuipicturebackend.manager.auth.model.SpaceUserPermissionConstant;
import com.jihui.jihuipicturebackend.model.dto.picture.*;
import com.jihui.jihuipicturebackend.model.entity.Picture;
import com.jihui.jihuipicturebackend.model.entity.PictureTagCategory;
import com.jihui.jihuipicturebackend.model.entity.Space;
import com.jihui.jihuipicturebackend.model.entity.User;
import com.jihui.jihuipicturebackend.model.enums.PictureReviewStatusEnum;
import com.jihui.jihuipicturebackend.model.vo.PictureVO;
import com.jihui.jihuipicturebackend.model.vo.SpaceVO;
import com.jihui.jihuipicturebackend.model.vo.UserVO;
import com.jihui.jihuipicturebackend.service.PictureService;
import com.jihui.jihuipicturebackend.service.SpaceService;
import com.jihui.jihuipicturebackend.service.UserService;
import com.jihui.jihuipicturebackend.utils.CaffeineCacheUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/picture")
@Api(tags = "图片相关接口")
public class PictureController {

    @Resource
    private PictureService pictureService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private AliYunAiApi aliYunAiApi;

    @Resource
    private SpaceService spaceService;

    @Resource
    private SpaceUserAuthManager spaceUserAuthManager;


    /**
     * 上传图片
     *
     * @param multipartFile
     * @param pictureUploadRequest
     * @param httpServletRequest
     * @return
     */
    @PostMapping("/upload")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_UPLOAD)
    @ApiOperation(value = "本地上传图片")
    public BaseResponse<PictureVO> uploadPicture(@RequestPart("file") MultipartFile multipartFile,
                                                 PictureUploadRequest pictureUploadRequest,
                                                 HttpServletRequest httpServletRequest) {
        User loginUser = (User) httpServletRequest.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        PictureVO pictureVO = pictureService.uploadPicture(multipartFile, pictureUploadRequest, loginUser);
        ThrowUtils.throwIf(pictureVO == null,
                new BusinessException(ErrorCode.OPERATION_ERROR, "图片上传失败"));
        return ResultUtils.success(pictureVO);
    }

    /**
     * 上传图片（url）
     *
     * @param pictureUploadRequest
     * @param httpServletRequest
     * @return
     */
    @PostMapping("/upload/url")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_UPLOAD)
    @ApiOperation(value = "Url上传图片")
    public BaseResponse<PictureVO> uploadPictureByUrl(@RequestBody PictureUploadRequest pictureUploadRequest,
                                                      HttpServletRequest httpServletRequest) {
        User loginUser = (User) httpServletRequest.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        String fileUrl = pictureUploadRequest.getFileUrl();
        PictureVO pictureVO = pictureService.uploadPicture(fileUrl, pictureUploadRequest, loginUser);
        ThrowUtils.throwIf(pictureVO == null,
                new BusinessException(ErrorCode.OPERATION_ERROR, "图片上传失败"));
        return ResultUtils.success(pictureVO);
    }

    /**
     * 删除图片
     *
     * @param pictureId
     * @return
     */
    @DeleteMapping("/delete/pictureId")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_UPLOAD)
    @ApiOperation(value = "删除图片")
    public BaseResponse<Boolean> deletePicture(@RequestParam("pictureId") Long pictureId,
                                               HttpServletRequest httpServletRequest) {
        // 校验参数
        ThrowUtils.throwIf(pictureId == null,
                new BusinessException(ErrorCode.PARAMS_ERROR, "图片ID不能为空"));
        User loginUser = (User) httpServletRequest.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        // 删除图片
        ThrowUtils.throwIf(!pictureService.deletePictureById(pictureId, loginUser),
                new BusinessException(ErrorCode.OPERATION_ERROR, "图片删除失败"));
//        ThrowUtils.throwIf(!pictureService.deletePictureById(pictureId),
//                new BusinessException(ErrorCode.OPERATION_ERROR,"图片删除失败"));
        return ResultUtils.success(true);
    }


    /**
     * 更新图片信息
     *
     * @param multipartFile
     * @param pictureUpdateRequest
     * @param httpServletRequest
     * @return
     */
    @PostMapping("/update")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_EDIT)
    @ApiOperation(value = "更新图片信息")
    public BaseResponse<PictureVO> updatePicture(@RequestPart("file") MultipartFile multipartFile,
                                                 PictureUpdateRequest pictureUpdateRequest,
                                                 HttpServletRequest httpServletRequest) {
        User loginUser = (User) httpServletRequest.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        PictureVO pictureVO = pictureService.updatePicture(multipartFile, pictureUpdateRequest, loginUser);
        ThrowUtils.throwIf(pictureVO == null,
                new BusinessException(ErrorCode.OPERATION_ERROR, "图片更新失败"));
        return ResultUtils.success(pictureVO);
    }


    /**
     * 根据图片ID获取图片信息
     *
     * @param pictureId
     * @return
     */
    @GetMapping("/get")
    //@CheckAuth(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation(value = "根据图片ID获取图片信息")
    public BaseResponse<PictureVO> getPictureById(@RequestParam("pictureId") Long pictureId,HttpServletRequest httpServletRequest) {
        ThrowUtils.throwIf(pictureId <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Picture picture = pictureService.getById(pictureId);
        ThrowUtils.throwIf(picture == null, ErrorCode.NOT_FOUND_ERROR);
        // 空间的图片，需要校验权限
        Space space = null;
        Long spaceId = picture.getSpaceId();
        if (spaceId != null) {
            boolean hasPermission = StpKit.SPACE.hasPermission(SpaceUserPermissionConstant.PICTURE_VIEW);
            ThrowUtils.throwIf(!hasPermission, ErrorCode.NO_AUTH_ERROR);
            space = spaceService.getById(spaceId);
            ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
        }
        // 获取权限列表
        User loginUser = (User) httpServletRequest.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        List<String> permissionList = spaceUserAuthManager.getPermissionList(space, loginUser);
        PictureVO pictureVO = pictureService.getPictureVO(picture, httpServletRequest);
        pictureVO.setPermissionList(permissionList);
        // 获取封装类
        return ResultUtils.success(pictureVO);
    }

    /**
     * 分页获取图片列表（仅管理员可用）
     */
    @PostMapping("/list/page")
    @CheckAuth(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation(value = "分页获取图片列表(仅管理员可用)")
    public BaseResponse<Page<Picture>> listPictureByPage(@RequestBody PictureQueryRequest pictureQueryRequest) {
        long current = pictureQueryRequest.getCurrent();
        long size = pictureQueryRequest.getPageSize();
        // 查询数据库
        // 管理员也不能查看私有空间的图片
        pictureQueryRequest.setNullSpaceId(true);
        Page<Picture> picturePage = pictureService.page(new Page<>(current, size),
                pictureService.getPictureQueryWrapper(pictureQueryRequest));
        return ResultUtils.success(picturePage);
    }

    /**
     * 分页获取图片vo信息(脱敏)
     *
     * @param pictureQueryRequest
     * @param httpServletRequest
     * @return
     */
    @PostMapping("/list/page/vo")
    @ApiOperation(value = "分页获取图片vo信息")
    public BaseResponse<Page<PictureVO>> getPictureByPage(@RequestBody PictureQueryRequest pictureQueryRequest,
                                                          HttpServletRequest httpServletRequest) {
        ThrowUtils.throwIf(ObjUtil.isEmpty(pictureQueryRequest),
                new BusinessException(ErrorCode.PARAMS_ERROR, "分页查询参数不能为空"));
        long current = pictureQueryRequest.getCurrent();
        long size = pictureQueryRequest.getPageSize();
        // 用户仅可以查看审核通过的图片，管理员可以查看所有图片
        User loginUser = (User) httpServletRequest.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        Long spaceId = pictureQueryRequest.getSpaceId();
        if (spaceId == null) {
            pictureQueryRequest.setNullSpaceId(true);
            if (ObjUtil.isEmpty(loginUser) || !loginUser.getUserRole().equals(UserConstant.ADMIN_ROLE)) {
                pictureQueryRequest.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());
            }
        } else {
            boolean hasPermission = StpKit.SPACE.hasPermission(SpaceUserPermissionConstant.PICTURE_VIEW);
            ThrowUtils.throwIf(!hasPermission, ErrorCode.NO_AUTH_ERROR);
        }
        QueryWrapper<Picture> pictureQueryWrapper = pictureService.getPictureQueryWrapper(pictureQueryRequest);

        Page<Picture> picturePage = pictureService.page(new Page<>(current, size), pictureQueryWrapper);

        // 将Picture转换为PictureVO
        Page<PictureVO> pictureListVO = pictureService.getPictureListVO(picturePage, httpServletRequest);
        return ResultUtils.success(pictureListVO);
    }

    /**
     * 分页获取图片vo信息(脱敏) + 缓存
     *
     * @param pictureQueryRequest
     * @param httpServletRequest
     * @return
     */
    @Deprecated
    @PostMapping("/list/page/vo/cache")
    //@CheckAuth(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation(value = "分页获取图片vo信息(加缓存)")
    public BaseResponse<Page<PictureVO>> getPictureByPageWithCache(@RequestBody PictureQueryRequest pictureQueryRequest,
                                                                   HttpServletRequest httpServletRequest) {
        ThrowUtils.throwIf(ObjUtil.isEmpty(pictureQueryRequest),
                new BusinessException(ErrorCode.PARAMS_ERROR, "分页查询参数不能为空"));
        long current = pictureQueryRequest.getCurrent();
        long size = pictureQueryRequest.getPageSize();
        // 用户仅可以查看审核通过的图片，管理员可以查看所有图片
        User loginUser = (User) httpServletRequest.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);

        if (ObjUtil.isEmpty(loginUser) || !loginUser.getUserRole().equals(UserConstant.ADMIN_ROLE)) {
            pictureQueryRequest.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());
        }
        // 1、先查询caffeine中是否有缓存
        String jsonStr = JSONUtil.toJsonStr(pictureQueryRequest);
        String hashKey = DigestUtils.md5DigestAsHex(jsonStr.getBytes());
        String cacheKey = "jihuipicture:getPictureByPage:" + hashKey;

        String caffeineCache = CaffeineCacheUtil.getCaffeineCache(cacheKey);
        if (caffeineCache != null) {
            Page<PictureVO> pictureListVO = JSONUtil.toBean(caffeineCache, Page.class);
            return ResultUtils.success(pictureListVO);
        }
        // 2、缓存中没有，查询redis
        String redisValue = stringRedisTemplate.opsForValue().get(cacheKey);
        if (redisValue != null) {
            CaffeineCacheUtil.setCaffeineCache(cacheKey, redisValue);
            Page<PictureVO> pictureListVO = JSONUtil.toBean(redisValue, Page.class);
            return ResultUtils.success(pictureListVO);
        }
        // 3、redis中没有，查询数据库
        QueryWrapper<Picture> pictureQueryWrapper = pictureService.getPictureQueryWrapper(pictureQueryRequest);
        Page<Picture> picturePage = pictureService.page(new Page<>(current, size), pictureQueryWrapper);
        // 将Picture转换为PictureVO
        Page<PictureVO> pictureListVO = pictureService.getPictureListVO(picturePage, httpServletRequest);
        // 缓存到caffeine和redis
        String cacheValue = JSONUtil.toJsonStr(pictureListVO);
        CaffeineCacheUtil.setCaffeineCache(cacheKey, cacheValue);
        int expireTime = 300 + RandomUtil.randomInt(0, 300);
        stringRedisTemplate.opsForValue().set(cacheKey, cacheValue, expireTime, java.util.concurrent.TimeUnit.SECONDS);
        return ResultUtils.success(pictureListVO);
    }


    /**
     * 编辑图片信息
     *
     * @param pictureEditRequest
     * @param httpServletRequest
     * @return
     */
    @PostMapping("/edit")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_EDIT)
    @ApiOperation(value = "编辑图片信息")
    public BaseResponse<Boolean> editPicture(@RequestBody PictureEditRequest pictureEditRequest,
                                             HttpServletRequest httpServletRequest) {
        ThrowUtils.throwIf(ObjUtil.isEmpty(pictureEditRequest),
                new BusinessException(ErrorCode.PARAMS_ERROR, "编辑图片参数不能为空"));

        // 仅管理员和用户自己可以编辑图片信息
        Long userId = pictureService.getById(pictureEditRequest.getId()).getUserId();
        User loginUser = (User) httpServletRequest.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        if (!userId.equals(loginUser.getId()) &&
                !loginUser.getUserRole().equals(UserConstant.ADMIN_ROLE)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无权限编辑图片信息");
        }
        // 处理和数据校验
        Picture picture = new Picture();
        BeanUtils.copyProperties(pictureEditRequest, picture);
        // 将list转为json字符串
        picture.setTags(JSONUtil.toJsonStr(pictureEditRequest.getTags()));
        picture.setEditTime(new Date());
        // 数据校验
        pictureService.validPicture(picture);
        // 重置审核状态
        pictureService.reviewStatus(picture, loginUser);
        // 更新数据库
        ThrowUtils.throwIf(!pictureService.updateById(picture),
                new BusinessException(ErrorCode.OPERATION_ERROR, "编辑图片失败"));
        return ResultUtils.success(true);
    }

    /**
     * 获取图片标签分类信息
     *
     * @return
     */
    @GetMapping("/tag_category")
    @ApiOperation(value = "获取图片标签分类信息")
    public BaseResponse<PictureTagCategory> listPictureTagCategory() {
        PictureTagCategory pictureTagCategory = new PictureTagCategory();
        List<String> tagList = Arrays.asList("热门", "搞笑", "生活", "高清", "艺术", "校园", "背景", "简历", "创意");
        List<String> categoryList = Arrays.asList("模板", "电商", "表情包", "素材", "海报");
        pictureTagCategory.setTagList(tagList);
        pictureTagCategory.setCategoryList(categoryList);
        return ResultUtils.success(pictureTagCategory);
    }


    /**
     * 图片审核状态
     *
     * @param pictureReviewStatusRequest
     * @param httpServletRequest
     * @return
     */
    @PostMapping("/review")
    @CheckAuth(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation(value = "图片审核状态")
    public BaseResponse<Boolean> pictureReviewStatus(@RequestBody PictureReviewStatusRequest pictureReviewStatusRequest,
                                                     HttpServletRequest httpServletRequest) {
        ThrowUtils.throwIf(ObjUtil.isEmpty(pictureReviewStatusRequest),
                new BusinessException(ErrorCode.PARAMS_ERROR, "图片审核状态参数不能为空"));

        User loginUser = (User) httpServletRequest.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);

        return ResultUtils.success(pictureService.pictureReviewStatus(pictureReviewStatusRequest, loginUser));
    }

    /**
     * 批量上传图片
     *
     * @param pictureUploadByBatchRequest
     * @param httpServletRequest
     * @return
     */
    @PostMapping("/upload/list")
    @CheckAuth(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation(value = "批量上传图片")
    public BaseResponse<Integer> uploadPictureByBatch(@RequestBody PictureUploadByBatchRequest pictureUploadByBatchRequest,
                                                      HttpServletRequest httpServletRequest) {
        ThrowUtils.throwIf(ObjUtil.isEmpty(pictureUploadByBatchRequest),
                new BusinessException(ErrorCode.PARAMS_ERROR, "批量上传图片参数不能为空"));
        User loginUser = (User) httpServletRequest.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);

        return ResultUtils.success(pictureService.pictureUploadByBatch(pictureUploadByBatchRequest, loginUser));
    }

    /**
     * 通过颜色搜索图片
     *
     * @param searchPictureByColorRequest
     * @param request
     * @return
     */
    @PostMapping("/search/color")
    @ApiOperation(value = "通过颜色搜索图片")
    public BaseResponse<List<PictureVO>> getPictureListByColor(@RequestBody SearchPictureByColorRequest searchPictureByColorRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(searchPictureByColorRequest == null, ErrorCode.PARAMS_ERROR);
        String picColor = searchPictureByColorRequest.getPicColor();
        Long spaceId = searchPictureByColorRequest.getSpaceId();
        User loginUser = (User) request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        List<PictureVO> result = pictureService.getPictureListByColor(spaceId, picColor, loginUser);
        return ResultUtils.success(result);
    }

    /**
     * 创建阔图任务
     *
     * @param createPictureOutPaintingTaskRequest
     * @param httpServletRequest
     * @return
     */
    @PostMapping("/create_task/out_painting")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_EDIT)
    @ApiOperation(value = "创建阔图任务")
    public BaseResponse<CreateOutPaintingTaskResponse> createOutPaintingTask(@RequestBody CreatePictureOutPaintingTaskRequest createPictureOutPaintingTaskRequest,
                                                                             HttpServletRequest httpServletRequest) {
        ThrowUtils.throwIf(createPictureOutPaintingTaskRequest == null, ErrorCode.PARAMS_ERROR);
        User loginUser = (User) httpServletRequest.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        CreateOutPaintingTaskResponse response = pictureService.createOutPaintingTask(createPictureOutPaintingTaskRequest, loginUser);
        return ResultUtils.success(response);
    }

    /**
     * 获取图片的阔图任务状态
     *
     * @param taskId
     * @return
     */
    @GetMapping("/out_painting/get_task")
    @ApiOperation(value = "获取图片的阔图任务状态")
    public BaseResponse<GetOutPaintingTaskResponse> getPictureOutPaintingTask(String taskId) {
        ThrowUtils.throwIf(StrUtil.isBlank(taskId), ErrorCode.PARAMS_ERROR);
        GetOutPaintingTaskResponse task = aliYunAiApi.getOutPaintingTask(taskId);
        return ResultUtils.success(task);
    }
}
